package com.gzx.spring.drools.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzx.risk.core.apis.result.jishu.JishuEdb003_v8;
import com.gzx.risk.core.apis.result.xinyisou.XinyisouScore95;
import com.gzx.risk.core.pojo.*;
import com.gzx.risk.core.service.ApisService;
import com.gzx.risk.core.service.RiskService;
import com.gzx.risk.core.service.UserLevelService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserLevelServiceImpl implements UserLevelService {
    @Resource
    private RiskService riskService;
    @Resource
    private ApisService apisService;

    private List<BinIntervalInfo> binIntervalInfo;

    private List<CrossBinningInfo> crossBinningInfo;

    private final ObjectMapper objectMapper;

    public UserLevelServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostConstruct
    public void init() {
        refreshData();
    }

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void refreshData() {
        try {
            binIntervalInfo = riskService.getBinIntervalInfo();
            crossBinningInfo = riskService.getCrossBiningInfo();
            log.info("定时刷新分值数据成功，当前时间：{}", LocalDateTime.now());
        } catch (Exception e) {
            log.error("定时刷新数据失败", e);
        }
    }

    @Override
    public UserLevelResultInfo getUserScoreByUid(String uid) {
        return riskService.getUserScoreResultByUid(uid);

    }

    /**
     * 用户分层
     * @param uid 用户id
     * @param oid 订单id
     * @throws Exception
     */
    @Override
    public void rateUserScore(Integer uid, Integer oid) throws Exception {
        UserInfo userInfo = riskService.findUserInfo(uid.longValue());
        OrderInfo riskOrder = riskService.findRiskOrder(oid);
        if (riskOrder == null || userInfo == null) {
            log.info("{}用户或{}订单不存在",uid,oid);
            return;
        }

        UserLevelResultInfo infoByIdCard = riskService.getUserScoreResultByIdCard(userInfo.getId());
        if (infoByIdCard != null) {
            infoByIdCard.setId(null);
            infoByIdCard.setOrdercode(riskOrder.getOrdercode());
            riskService.saveUserScore(infoByIdCard);
            return;
        }

        String json = apisService.getScore95s(userInfo.getName(), userInfo.getId(), userInfo.getPhone());
        XinyisouScore95 score95s = objectMapper.readValue(json, XinyisouScore95.class);
        String jsonV8 = apisService.getEdb003_v8(userInfo.getName(), userInfo.getId(), userInfo.getPhone());
        JishuEdb003_v8 edb003_v8 = objectMapper.readValue(jsonV8, JishuEdb003_v8.class);

        log.info("【{}{}】用户信用分：{},欺诈分：{}",userInfo.getName(),uid,score95s.getScore(),edb003_v8.getScore());

        Integer tianyuSortOrder = getSortOrder(edb003_v8.getScore(), "TIANYU");
        Integer puyuSortOrder = getSortOrder(score95s.getScore(), "PUYU");
        CrossBinningInfo binningInfo = getCrossBinningInfo(tianyuSortOrder,puyuSortOrder);

        UserLevelResultInfo userLevelResult = new UserLevelResultInfo();
        userLevelResult.setUid(uid);
        userLevelResult.setOrdercode(riskOrder.getOrdercode());
        userLevelResult.setName(userInfo.getName());
        userLevelResult.setIdCard(userInfo.getId());
        userLevelResult.setPhone(userInfo.getPhone());
        userLevelResult.setTianyuScore(edb003_v8.getScore().toString());
        userLevelResult.setPuyuScore(score95s.getScore().toString());
        userLevelResult.setGrade(binningInfo.getGrade());
        userLevelResult.setPassRate(binningInfo.getPassRate());
        userLevelResult.setMachine(binningInfo.getMachine());
        userLevelResult.setPrepayPeriods(binningInfo.getPrepayPeriods());
        userLevelResult.setMinDeposit(binningInfo.getMinDeposit());
        userLevelResult.setScreenInsurance(binningInfo.getScreenInsurance());
        riskService.saveUserScore(userLevelResult);
    }

    private Integer getSortOrder(Double score, String type) {
        for (BinIntervalInfo info : binIntervalInfo) {
            if (type.equals(info.getType())) {
                Double minVal = info.getMinVal();
                Double maxVal = info.getMaxVal();
                // 检查分值是否在区间内：minVal <= score < maxVal（maxVal为null表示无穷大）
                boolean isInRange = score >= minVal && (maxVal == null || score < maxVal);
                if (isInRange) {
                    return info.getSortOrder();
                }
            }
        }
        return null;
    }

    private CrossBinningInfo getCrossBinningInfo(Integer xAxis, Integer yAxis) {
        for (CrossBinningInfo info : crossBinningInfo) {
            if (info.getXAxis().equals(xAxis) && info.getYAxis().equals(yAxis)) {
                return info;
            }
        }
        return new CrossBinningInfo();
    }
}
